package com.android.gufengmall.my;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.android.gufengmall.App;
import com.android.gufengmall.R;
import com.android.gufengmall.bean.UserBean;
import com.android.gufengmall.gen.DaoSession;
import com.android.gufengmall.gen.UserBeanDao;
import com.android.gufengmall.login.LoginActivity;
import com.android.gufengmall.utils.GlideEngine;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.style.PictureSelectorUIStyle;
import com.luck.picture.lib.tools.MediaUtils;

import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class MyFragment extends Fragment {

    private static final String TAG = "MyFragment";

    private App mMyApp;
    private DaoSession mDaoSession;
    private UserBeanDao mUserDao;
    private ActivityResultLauncher<Intent> launcherResult;

    private ImageView mImgPhoto;
    private TextView mTvName;
    private TextView mTvAge;
    private TextView mTvSex;
    private RelativeLayout mRatAddress;
    private RelativeLayout mRatOrder;
    private RelativeLayout mRatForum;
    private RelativeLayout mRatOut;
    private LinearLayout mLlUserInfo;
    private UserBean mUserBean;
    private String mUsername;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

    private String mRealPath;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_my, container, false);

        initView(root);
        initData();
        initListener();

        return root;
    }

    private void initListener() {
        mRatAddress.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AddressActivity.class);
            startActivity(intent);
        });
        mRatOrder.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), OrderActivity.class);
            startActivity(intent);
        });
        mRatForum.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(),ForumActivity.class);
            intent.putExtra("name",mUsername);
            startActivity(intent);
        });
        mRatOut.setOnClickListener(v -> {
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.hint));
            dialog.setMessage(requireContext().getString(R.string.sure_out));
            dialog.setPositiveButton(requireContext().getString(R.string.sure), (dialog1, which) -> {
                mEditor.putBoolean("autoLogin", false);
                mEditor.apply();
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
        mImgPhoto.setOnClickListener(v -> {
            PictureSelector.create(MyFragment.this)
                    .openGallery(PictureMimeType.ofImage())
                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                    .setPictureUIStyle(PictureSelectorUIStyle.ofDefaultStyle())
                    .selectionMode(PictureConfig.SINGLE)// 单选
                    .isSingleDirectReturn(true)// 单选模式下是否直接返回
                    .isCamera(true)
                    .isPreviewImage(true)// 可预览图片
                    .isZoomAnim(true)// 图片列表点击 缩放效果
                    .forResult(launcherResult);
        });
        mLlUserInfo.setOnClickListener(v -> {
            View view = LayoutInflater.from(requireContext()).inflate(R.layout.item_my_info_dialog, null, false);
            EditText edtName = view.findViewById(R.id.edt_name);
            EditText edtAge = view.findViewById(R.id.edt_age);
            EditText edtSex = view.findViewById(R.id.edt_sex);
            edtName.setText(mUserBean.getUserNick());
            edtAge.setText(mUserBean.getAge());
            edtSex.setText(mUserBean.getSex());
            AlertDialog.Builder dialog = new AlertDialog.Builder(requireContext());
            dialog.setTitle(requireContext().getString(R.string.hint));
            dialog.setView(view);
            dialog.setPositiveButton(requireContext().getString(R.string.sure), (dialog1, which) -> {
                String name = edtName.getText().toString().trim();
                String age = edtAge.getText().toString().trim();
                String sex = edtSex.getText().toString().trim();
                mUserBean.setUserNick(name);
                mUserBean.setAge(age);
                mUserBean.setSex(sex);
                mTvName.setText(name);
                mTvAge.setText(age);
                mTvSex.setText(sex);
                mUserDao.update(mUserBean);
            });
            dialog.setNegativeButton(requireContext().getString(R.string.cancel), null);
            dialog.create().show();
        });
    }

    private void initData() {
        mMyApp = (App) getActivity().getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mUserDao = mDaoSession.getUserBeanDao();

        launcherResult = createActivityResultLauncher();

        mSharedPreferences = getActivity().getSharedPreferences("autoLogin", MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        String username = mSharedPreferences.getString("username", "");
        if (!username.isEmpty()) {
            mUsername = username;
        } else {
            mUsername = getActivity().getIntent().getExtras().getString("username");
        }
        List<UserBean> list = mUserDao.queryBuilder().where(UserBeanDao.Properties.UserName.eq(mUsername)).list();
        for (UserBean userBean : list) {
            if (userBean.getUserName().equals(mUsername)) {
                mUserBean = userBean;
                mTvName.setText(userBean.getUserNick() == null ? "随机昵称" : userBean.getUserNick());
                mTvAge.setText(userBean.getAge());
                mTvSex.setText(userBean.getSex());
                Glide.with(requireContext()).load(BitmapFactory.decodeFile(userBean.getUserPhoto()))
                        .dontAnimate().error(R.drawable.icon_photo).centerCrop().into(mImgPhoto);
            }
        }

    }


    //接收到选择的图片
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    int resultCode = result.getResultCode();
                    if (resultCode == -1) {
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(result.getData());
                        for (LocalMedia media : selectList) {
                            if (media.getWidth() == 0 || media.getHeight() == 0) {
                                if (PictureMimeType.isHasImage(media.getMimeType())) {
                                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                                    media.setWidth(imageExtraInfo.getWidth());
                                    media.setHeight(imageExtraInfo.getHeight());
                                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                    MediaExtraInfo videoExtraInfo = MediaUtils.getVideoSize(getContext(), media.getPath());
                                    media.setWidth(videoExtraInfo.getWidth());
                                    media.setHeight(videoExtraInfo.getHeight());
                                }
                            }
                            mRealPath = media.getRealPath();

                            Glide.with(requireContext()).load(BitmapFactory.decodeFile(mRealPath))
                                    .dontAnimate().error(R.drawable.icon_photo).centerCrop().into(mImgPhoto);
                            mUserBean.setUserPhoto(mRealPath);
                            mUserDao.update(mUserBean);
                        }
                    }
                });
    }

    private void initView(View view) {
        mImgPhoto = view.findViewById(R.id.img_photo);
        mTvName = view.findViewById(R.id.tv_my_name);
        mTvAge = view.findViewById(R.id.tv_my_age);
        mTvSex = view.findViewById(R.id.tv_my_sex);
        mRatAddress = view.findViewById(R.id.rat_address);
        mRatOrder = view.findViewById(R.id.rat_order);
        mRatForum = view.findViewById(R.id.rat_forum);
        mRatOut = view.findViewById(R.id.rat_out);
        mLlUserInfo = view.findViewById(R.id.ll_user_info);

    }
}